package com.yuxl.common.core.handler;

import com.yuxl.common.core.domain.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局异常处理器
 * 使用@RestControllerAdvice注解捕获全局异常
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理所有未捕获的异常
     * @param e 异常
     * @param exchange ServerWebExchange对象
     * @return 统一响应R
     */
    @ExceptionHandler(Exception.class)
    public Mono<ResponseEntity<R<Void>>> handleException(Exception e, ServerWebExchange exchange) {
        log.error("系统异常: {}", e.getMessage(), e);
        R<Void> response = new R<>("系统内部错误: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        return Mono.just(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response));
    }

    /**
     * 处理权限不足异常
     * @param e AccessDeniedException异常
     * @param exchange ServerWebExchange对象
     * @return 统一响应R
     */
    @ExceptionHandler(AccessDeniedException.class)
    public Mono<ResponseEntity<R<Void>>> handleAccessDeniedException(AccessDeniedException e, ServerWebExchange exchange) {
        log.warn("权限不足: {}", e.getMessage());
        R<Void> response = new R<>("权限不足: " + e.getMessage(), HttpStatus.FORBIDDEN);
        return Mono.just(ResponseEntity.status(HttpStatus.FORBIDDEN).body(response));
    }

    /**
     * 处理空指针异常
     * @param e NullPointerException异常
     * @param exchange ServerWebExchange对象
     * @return 统一响应R
     */
    @ExceptionHandler(NullPointerException.class)
    public Mono<ResponseEntity<R<Void>>> handleNullPointerException(NullPointerException e, ServerWebExchange exchange) {
        log.error("空指针异常: {}", e.getMessage(), e);
        R<Void> response = new R<>("操作失败: 系统内部错误", HttpStatus.INTERNAL_SERVER_ERROR);
        return Mono.just(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response));
    }

    /**
     * 处理业务异常
     * @param e NullPointerException异常
     * @param exchange ServerWebExchange对象
     * @return 统一响应R
     */
    @ExceptionHandler(ApiException.class)
    public Mono<ResponseEntity<R<Void>>> handleApiException(ApiException e, ServerWebExchange exchange) {
        log.error("处理业务异常: {}", e.getMessage(), e);
        R<Void> response = new R<>(e.getMessage(), e.getStatus());
        return Mono.just(ResponseEntity.status(e.getStatus()).body(response));
    }

}
